import { ref, reactive, onMounted, nextTick } from 'vue'
import { EditType } from '@/type/BaseEnum'
import { saveExpressNumApi, getExpressListApi } from '@/api/logistics'
import useInstance from '@/hooks/useInstance'
import { LogisticParm } from '@/api/logistics/LogisticModel'
import { Toast } from '@nutui/nutui'
import { useRoute, useRouter } from 'vue-router'

export default function useSetting() {
	const route = useRoute()
	const kuidiRef = ref<{ show: (type?: string, row?: any) => void }>()
	const router = useRouter()
	const rowData = ref<any>()
	const isVisible = ref<boolean>(false)
	const ruleForm = ref()
	const { global } = useInstance()
	const formData = reactive<LogisticParm>({
		id: undefined,
		order_id: undefined,
		express_num: undefined,
		express_company: undefined
	})
	const rules = {
		express_num: [{ required: true, message: '请输入快递单号' }],
		express_company: [{ required: true, message: '请输入快递公司' }]
	}
	//新增
	const editBtn = async (row: any) => {
		kuidiRef.value?.show(EditType.EDIT, row)
		// let res = await saveExpressNumApi({ ...formData })
		// if (res && res.code == 0) {
		// 	Toast.success('编辑成功')
		// 	// 返回上一页面
		// 	router.go(-1)
		// } else {
		// 	Toast.fail('编辑失败')
		// }
	}

	const submit = () => {
		formData.order_id = rowData.value.order_id as any
		// editBtn();
		ruleForm.value.validate().then(async ({ valid, errors }: any) => {
			if (valid) {
				let res = await saveExpressNumApi({ ...formData })
				if (res && res.code == 0) {
					Toast.success('编辑成功')
				} else {
					Toast.fail('编辑失败')
				}
				isVisible.value = false
			} else {
				console.log('error submit!!', errors)
			}
		})
	}
	const getData = async () => {
		let res = await getExpressListApi({
			order_id: rowData.value.order_id as any
		})
		if (res && res.code == 0) {
			nextTick(() => {
				//把要编辑的数据复制到表单绑定的对象
				global.$objCoppy(res.result, formData)
			})
		}
	}

	onMounted(() => {})
	return {
		editBtn,
		formData,
		submit,
		ruleForm,
		rules,
		rowData,
		isVisible,
		getData
	}
}
